package cn.com.hsm.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.nlpcn.commons.lang.pinyin.Pinyin;

import com.alibaba.fastjson.JSON;

/**
 * 数据排序
 * @author sunq
 *
 */
public class DataSort{
	
	/**
	 * 解决数据中包含中英文混合排序
	 * @param userList
	 * @return
	 */
	public static Map<String, List<User>> getEnCnSort(List<User> userList) {
		Map<String, List<User>> maps = new TreeMap<String, List<User>>();
		for (User user : userList) {
			String name = user.getName().trim();
			char fc = Character.toUpperCase(name.charAt(0));
			String key = null;
			if (fc >= 'A' && fc <= 'Z') {
				key = String.valueOf(fc);
			} else {
				key = Pinyin.pinyin(name.substring(0, 1)).get(0);
				if (key == null) {
					key = "其他";
				} else {
					fc = Character.toUpperCase(key.charAt(0));
					if (fc >= 'A' && fc <= 'Z') {
						key = String.valueOf(fc);
					} else {
						key = "其他";
					}
				}
			}
			List<User> list = maps.get(key);
			if (list == null) {
				list = new ArrayList<>();
				maps.put(key, list);
			}
			list.add(user);
		}

		for (Entry<String, List<User>> e : maps.entrySet()) {
			e.getValue().sort((r1, r2) -> {
				String n1 = Pinyin.list2String(Pinyin.firstChar(r1.getName()));
				String n2 = Pinyin.list2String(Pinyin.firstChar(r2.getName()));
				return n1.compareTo(n2);
			});
		}
		return maps;
	}

	public static void main(String[] args) {
		List<User> list = new ArrayList<User>();
		User u = new User();
		u.setName("孙强");
		list.add(u);
		u = new User();
		u.setName("马书文");
		list.add(u);
		u = new User();
		u.setName("hehe");
		list.add(u);
		u = new User();
		u.setName("大贺");
		list.add(u);
		System.out.println(JSON.toJSONString(getEnCnSort(list)));
	}
}

class User {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
